$(function() {

    $(".form-myt-sale-sale-delivery-bpmInput").data("formOptions", {
        updateTotalAmount : function() {
            var $form = $(this);

            var $grid = $form.find(".grid-myt-sale-sale-delivery-bpmInput");
            var userData = {
                "commodity.display" : "合计："
            };
            // 更新表格汇总统计数据

            userData.quantity = $grid.jqGrid('sumColumn', 'quantity');
            userData.taxAmount = $grid.jqGrid('sumColumn', 'taxAmount');
            userData.amount = $grid.jqGrid('sumColumn', 'amount');
            userData.originalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
            userData.discountAmount = $grid.jqGrid('sumColumn', 'discountAmount');

            $grid.jqGrid("footerData", "set", userData, true);

            var chargeLogisticsAmount = Util.parseFloatValDefaultZero($form.find("input[name='chargeLogisticsAmount']"));
            var discountAmount = Util.parseFloatValDefaultZero($form.find("input[name='discountAmount']"))
            var commodityAmount = userData.amount;
            var totalTaxAmount = userData.taxAmount
            var commodityAndTaxAmount = commodityAmount + totalTaxAmount;
            var totalAmount = commodityAndTaxAmount + chargeLogisticsAmount;
            $form.setFormDatas({
                commodityAmount : commodityAmount,
                totalTaxAmount : totalTaxAmount,
                commodityAndTaxAmount : commodityAndTaxAmount,
                discountAmount : userData.discountAmount,
                totalOriginalAmount : userData.originalAmount,
                totalAmount : totalAmount,
                payedAmount : totalAmount
            });
        },
        bindEvents : function() {
            var $form = $(this);
            var $grid = $form.find(".grid-myt-sale-sale-delivery-bpmInput");

            $form.find("input[name='chargeLogisticsAmount']").keyup(function() {
                $form.data("formOptions").updateTotalAmount.call($form);
            });

            Biz.setupCustomerProfileSelect($form);
            
            //扫描枪输入处理
            $form.find("input[name='barcode']").barcodeScanSupport({
                onEnter : function() {
                    var code = $(this).val();
                    if (code != '') {
                        var data = Biz.queryCacheCommodityDatas(code);
                        if (data && data.length > 0) {
                            var rowdata = data[0];
                            var ids = $grid.jqGrid('getDataIDs');
                            var targetRowdata = null;
                            var targetRowid = null;
                            $.each(ids, function(i, id) {
                                var item = $grid.jqGrid('getRowData', id);
                                if (item['commodity.barcode'] == rowdata['barcode']) {
                                    if (item['gift'] != 'true') {
                                        targetRowid = id;
                                        targetRowdata = item;
                                        return false;
                                    }
                                }
                            });

                            if (targetRowdata) {
                                targetRowdata.quantity = Number(targetRowdata.quantity) + 1;
                                $grid.data("gridOptions").calcRowAmount.call($grid, targetRowdata);
                                $grid.jqGrid('setRowData', targetRowid, targetRowdata);
                            } else {
                                var newdata = {
                                    'commodity.id' : rowdata.id,
                                    'commodity.sku' : rowdata.sku,
                                    'commodity.barcode' : rowdata.barcode,
                                    'measureUnit' : rowdata.measureUnit,
                                    'storageLocation.id' : rowdata['storageLocation.id'],
                                    'commodity.display' : rowdata.display,
                                    'price' : rowdata.price,
                                    'discountRate' : 0,
                                    'taxRate' : 0,
                                    'quantity' : 1
                                }
                                // FLAG
                                $grid.data("gridOptions").calcRowAmount.call($grid, newdata);
                                var newid = $grid.jqGrid('insertNewRowdata', newdata);
                                var idx = $grid.find("tr[id='" + newid + "'] >td.jqgrid-rownum").html().trim();
                                $grid.jqGrid('setRowData', newid, {
                                    subVoucher : 100 + idx * 10
                                });
                            }
                            $form.data("formOptions").updateTotalAmount.call($form);
                        }
                        $(this).focus();
                    }
                }
            });
           
            // 从销售订单选取
            $form.find(".btn-select-sale-order").click(function() {
                var $boxOrderDetailId = $form.find("input[name='boxOrderDetail.id']");
                var boxOrderDetailId = $boxOrderDetailId.val();
                if (boxOrderDetailId != '') {
                    if (confirm("一个销售单只允许从单个销售订单选取，重新选取将清空当前相关数据以新选择订单数据覆盖，确认继续？")) {
                        $grid.clearGridData();
                        $form.data("formOptions").updateTotalAmount.call($form);
                    }
                }

                $(this).popupDialog({
                    url : WEB_ROOT + '/myt/sale/sale-delivery!forward?_to_=selectBoxOrderDetails',
                    title : '选取销售订单',
                    callback : function(data) {
                        var master = data.master;
                        var rows = data.rows;
                        $boxOrderDetailId.val(master.id);

                        $form.setFormDatas({
                            'receivePerson' : master['boxOrder.receivePerson'],
                            'mobilePhone' : master['boxOrder.mobilePhone'],
                            'postCode' : master['boxOrder.postCode'],
                            'title' : "[" + master['reserveDeliveryTime'].substr(0, 7) + "]" + master['boxOrder.title'],
                            'deliveryAddr' : master['boxOrder.deliveryAddr'],
                            'customerProfile.id' : master['boxOrder.customerProfile.id'],
                            'customerProfile.display' : master['boxOrder.customerProfile.display'],
                            'referenceVoucher' : master['boxOrder.orderSeq'],
                            'reserveDeliveryTime':master['reserveDeliveryTime'],
                            'referenceSource' : 'MYT',
                            'memo' : master['boxOrder.customerMemo']
                        }, true);

                        $.each(rows, function(i, row) {

                            row['storageLocation.id'] = row['defaultStorageLocation.id'] ? row['defaultStorageLocation.id'] : row['commodity.defaultStorageLocation.id'];
                            row['measureUnit'] = row['commodity.measureUnit'];
                            row['boxOrderDetailCommodity.id'] = row['id'];
                            if (row['gift'] == 'true') {
                                row['discountRate'] = 100;
                                row['price'] = 0;
                            } else {
                                row['discountRate'] = 0;
                            }

                            row['taxRate'] = 0;
                            $grid.data("gridOptions").calcRowAmount.call($grid, row);
                            var newid = $grid.jqGrid('insertNewRowdata', row);
                            var idx = $grid.find("tr[id='" + newid + "'] >td.jqgrid-rownum").html().trim();
                            $grid.jqGrid('setRowData', newid, {
                                subVoucher : 100 + idx * 10
                            });
                            $form.data("formOptions").updateTotalAmount.call($form);
                        });
                    }
                })
            });
         //  从退换货单选取
            $form.find(".btn-select-sale-return").click(function() {
                var $saleReturnId = $form.find("input[name='saleReturn.id']");
                var saleReturnId = $saleReturnId.val();
                if (saleReturnId!= '') {
                    if (confirm("只允许选取一个退换货单，确认清空并覆盖数据？")) {
                        $grid.clearGridData();
                        $form.data("formOptions").updateTotalAmount.call($form);
                    }else{
                    	return;
                    }
                }
                $(this).popupDialog({
                    url : WEB_ROOT + '/myt/sale/sale-delivery!forward?_to_=selectSaleReturn',
                    title : '选取退换货单',
                    callback : function(data) {
                        var master = data.master;
                        var rows = data.rows;
                        $saleReturnId.val(master.id);

                        $form.setFormDatas({
                            'receivePerson' : master['receivePerson'],
                            'mobilePhone' : master['mobilePhone'],
                            'postCode' : master['postCode'],
                            'deliveryAddr' : master['deliveryAddr'],
                            'customerProfile.id' : master['customerProfile.id'],
                            'customerProfile.display' : master['customerProfile.display'],
                            'referenceVoucher' : master['voucher'],
                            'referenceSource' : 'MYT',
                            'memo' : master['memo']
                        }, true);

                        $.each(rows, function(i, row) {

                            //row['storageLocation.id'] = row['storageLocation.id'];
                            row['measureUnit'] = row['commodity.measureUnit'];
                            row['saleReturnDetail.id'] = row['id'];
                            row['price'] = 0;
                            row['discountRate'] = 0;
                            row['taxRate'] = 0;
                            $grid.data("gridOptions").calcRowAmount.call($grid, row);
                            var newid = $grid.jqGrid('insertNewRowdata', row);
                            var idx = $grid.find("tr[id='" + newid + "'] >td.jqgrid-rownum").html().trim();
                            $grid.jqGrid('setRowData', newid, {
                                subVoucher : 100 + idx * 10
                            });
                            $form.data("formOptions").updateTotalAmount.call($form);
                        });
                    }
                })
            });

            //按金额自动分摊折扣金额
            $form.find(".btn-discount-by-amount").click(function() {
                if ($grid.jqGrid("isEditingMode", true)) {
                    return false;
                }
                
                  //按照“原价金额”的比率计算更新每个行项的折扣额，注意最后一条记录需要以减法计算以修正小数精度问题
                    var discountAmount = $form.find("input[name='discountAmount']").val();
                    var totalOriginalAmount = $grid.jqGrid('sumColumn', 'originalAmount');
                    var perDiscountAmount = MathUtil.mul(MathUtil.div(discountAmount, totalOriginalAmount, 5), 100);
                    var lastrowid = null;
                    var totalDiscountAmount = 0;
                    var ids = $grid.jqGrid("getDataIDs");
                    $.each(ids, function(i, id) {
                        var rowdata = $grid.jqGrid("getRowData", id);
                        if (rowdata['gift'] != 'true' && rowdata['commodity.id'] != '') {
                            rowdata['discountRate'] = perDiscountAmount;
                            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'discountRate');
                            $grid.jqGrid('setRowData', id, rowdata);
                            totalDiscountAmount = MathUtil.add(totalDiscountAmount, rowdata['discountAmount']);
                            lastrowid = id;
                        }
                    });
                    //最后一条记录需要以减法计算以修正小数精度问题
                    if (lastrowid) {
                        var rowdata = $grid.jqGrid("getRowData", lastrowid);
                        rowdata['discountAmount'] = MathUtil.sub(discountAmount, MathUtil.sub(totalDiscountAmount, rowdata['discountAmount']));
                        $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, 'discountAmount');
                        $grid.jqGrid('setRowData', lastrowid, rowdata);
                    }

                    $form.data("formOptions").updateTotalAmount.call($form);
             });

            //打印快递单
            $form.find(".btn_express_print_QF").click(function() {
                if (confirm("确认调用票据打印程序打印当前快递单吗?")) {
                    var url = WEB_ROOT + "/rpt/jasper-report!generate?format=XLS&report=EXPRESS_QUANFENG&contentDisposition=attachment";
                    url += "&reportParameters['SALE_DELIVERY_IDS']=" + $form.find("input[name='voucher']").val();
                    window.open(url, "_blank");
                }
            });
            $form.find(".btn_express_print_ST").click(function() {
                if (confirm("确认调用票据打印程序打印当前快递单吗?")) {
                    var url = WEB_ROOT + "/rpt/jasper-report!generate?format=XLS&report=EXPRESS_SHENTONG&contentDisposition=attachment";
                    url += "&reportParameters['SALE_DELIVERY_IDS']=" + $form.find("input[name='voucher']").val();
                    window.open(url, "_blank");
                }
            });
            //打印发货单
            $form.find(".btn_delivery_print").click(function() {
                if (confirm("确认打印发货清单?")) {
                    var url = WEB_ROOT + "/rpt/jasper-report!generate?format=XLS&report=SALE_DELIVERY_COMMODITY_LIST&contentDisposition=attachment";
                    url += "&reportParameters['SALE_DELIVERY_IDS']=" + $form.find("input[name='voucher']").val();
                    window.open(url, "_blank");
                }
            });
            // TODO 自动分配代理商 
            $form.find(".btn_auto_allot_partner").click(function() {
                var addr = $form.find("input[name='deliveryAddr']").val();
                var gc = new BMap.Geocoder();
                gc.getPoint(addr, function(point){
                    if(point){
                        geo = point.lat+","+point.lng;
                        $.post(WEB_ROOT + "/myt/sale/sale-delivery!getMinimumDistancePartner","geocode="+geo,function(data){
                            if(data && data!='NULL'){
                                $form.setFormDatas({
                                    'agentPartner.display' : data.display,
                                    'agentPartner.id' : data.id
                                }, true);
                            }else{
                                alert(addr + " 附近没有代理商");
                            }
                        },"json");
                    }else{
                        alert("无法定位："+addr);
                    }
                }, "北京");
            });

            $form.find("input[name='accountSubject.display']").treeselect({
                url : WEB_ROOT + "/myt/finance/account-subject!findPaymentAccountSubjects",
                callback : {
                    onSingleClick : function(event, treeId, treeNode) {
                        $form.setFormDatas({
                            'accountSubject.id' : treeNode.id,
                            'accountSubject.display' : treeNode.display
                        }, true);
                    },
                    onClear : function(event) {
                        $form.setFormDatas({
                            'accountSubject.id' : '',
                            'accountSubject.display' : ''
                        }, true);
                    }
                }
            });
        },
        preValidate : function() {
            var $form = $(this);
            var $agentPartner = $form.find("input[name='agentPartner.id']");
            var $paymentAccountSubjects = $form.find("input[name='accountSubject.id']");
            if ($payedAmount.val() != '' && $paymentAccountSubjects.val() == '') {
                bootbox.alert("如有收款金额则必须选取收款账户");
                return false;
            }
        }
    });

    $(".grid-myt-sale-sale-delivery-bpmInput").data("gridOptions", {
        calcRowAmount : function(rowdata, src) {
            rowdata['originalAmount'] = MathUtil.mul(rowdata['price'], rowdata['quantity']);
            if (src == 'discountAmount') {
                rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
                rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
            } else if (src == 'amount') {
                rowdata['discountAmount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['amount']);
                rowdata['discountRate'] = MathUtil.div(rowdata['discountAmount'], rowdata['originalAmount'], 5) * 100;
            } else {
                rowdata['discountAmount'] = MathUtil.div(MathUtil.mul(rowdata['discountRate'], rowdata['originalAmount']), 100);
                rowdata['amount'] = MathUtil.sub(rowdata['originalAmount'], rowdata['discountAmount']);
            }
            rowdata['taxAmount'] = MathUtil.div(MathUtil.mul(rowdata['amount'], rowdata['taxRate']), 100);
            rowdata['commodityAndTaxAmount'] = MathUtil.add(rowdata['amount'], rowdata['taxAmount']);
        },
        updateRowAmount : function(src) {
            var $grid = $(this);
            var rowdata = $grid.jqGrid("getEditingRowdata");
            $grid.data("gridOptions").calcRowAmount.call($grid, rowdata, src);
            $grid.jqGrid("setEditingRowdata", rowdata);
        },
        batchEntitiesPrefix : "saleDeliveryDetails",
        url : function() {
            var pk = $(this).attr("data-pk");
            if (pk) {
                return WEB_ROOT + "/myt/sale/sale-delivery!saleDeliveryDetails?id=" + pk + "&clone=" + $(this).attr("data-clone");
            }
        },
        colModel : [ {
            label : '所属销售单主键',
            name : 'saleDelivery.id',
            hidden : true,
            hidedlg : true,
            editable : true,
            formatter : function(cellValue, options, rowdata, action) {
                var pk = $(this).attr("data-pk");
                return pk ? pk : "";
            }
        }, {
            name : 'commodityStock.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'boxOrderDetailCommodity.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'saleReturnDetail.id',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.sku',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            name : 'commodity.barcode',
            hidden : true,
            hidedlg : true,
            editable : true
        }, {
            label : '行项号',
            name : 'subVoucher',
            width : 50,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $el = $(elem);
                    if ($el.val() == '') {
                        var $jqgrow = $el.closest(".jqgrow");
                        var idx = $jqgrow.find(">td.jqgrid-rownum").html().trim();
                        $el.val(100 + idx * 10);
                    }
                }
            },
            align : 'center'
        },{
            label : '商品',
            name : 'commodity.display',
            width : 200,
            editable : true,
            editrules : {
                required : true
            },
            editoptions : {
                placeholder : '输入商品信息提示选取或双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    // 弹出框的选取回调函数
                    var selectCommodity = function(item) {
                        
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        var oldQuantity = null;// 如果是已经选择过的商品，那么这是哪个商品的数量
                        var idx=1;
                        for(i=0; i<ids.length; i++){
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['commodity.sku'] == row['commodity.sku'] && 
                                item.batchNo == row.batchNo && 
                                item['storageLocation.id'] == row['storageLocation.id'] && 
                                item.gift.toString() == row['gift'].toString()){
                                 // SKU，批次号，库存地一致，是否赠品一致即认为是同一商品
                                existRowId = ids[i];
                                oldQuantity = row.quantity;
                                break;
                            }
                           
                        }
                        
                        if(existRowId){
                            $grid.jqGrid("setRowData", existRowId, {
                                'quantity' : MathUtil.add(oldQuantity,1)
                            });
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            $grid.jqGrid("setRowData", existRowId, myrowdata);
                        }else{
                            var myrowdata;
                            if(item.gift){
                                // 是赠品
                                myrowdata = {  
                                        'commodity.sku' : item['commodity.sku'],//商品唯一性标识
                                        'commodity.id' : item['commodity.id'],
                                        'commodity.barcode' : item['commodity.barcode'],
                                        'commodity.sku' : item['commodity.sku'],
                                        'commodity.display' : item['commodity.display'],
                                        'commodity.title' : item['commodity.title'],
                                        'measureUnit' : item['commodity.measureUnit'],
                                        'storageLocation.id' : item['storageLocation.id'],
                                        'batchNo' : item['batchNo'],
                                        'expireDate' : item['expireDate'],
                                        'quantity' : 1,
                                        'discountRate' : 0,
                                        'taxRate' : 0,
                                        'gift' : item.gift,
                                        'price' : 0,
                                        'originalAmount' : 0,
                                        'discountRate' : 0,
                                        'discountAmount' : 0,
                                        'amount' : 0,
                                        'taxAmount' : 0,
                                        'commodityAndTaxAmount' : 0
                                };
                            }else{
                                // 不是赠品
                                myrowdata = {  
                                        'commodity.sku' : item['commodity.sku'],//商品唯一性标识
                                        'commodity.id' : item['commodity.id'],
                                        'commodity.barcode' : item['commodity.barcode'],
                                        'commodity.sku' : item['commodity.sku'],
                                        'commodity.display' : item['commodity.display'],
                                        'commodity.title' : item['commodity.title'],
                                        'price' : item['commodity.price'],
                                        'measureUnit' : item['commodity.measureUnit'],
                                        'storageLocation.id' : item['storageLocation.id'],
                                        'batchNo' : item['batchNo'],
                                        'expireDate' : item['expireDate'],
                                        'quantity' : 1,
                                        'discountRate' : 0,
                                        'taxRate' : 0
                                };
                            }
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("insertNewRowdata", myrowdata);
                           
                        }
                        
                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                         var idx = $grid.find("tr[id='" + existRowId + "'] >td.jqgrid-rownum").html().trim();
                         $grid.jqGrid('setRowData', existRowId, {
                            subVoucher : 100 + idx * 10
                        });
                    }
                    // 自动完成框的选取回调函数
                    var autocompleteSelectCommodity = function(item) {
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        
                        var existRowId = null;// 如果是已经选择过的商品，那么这是哪个商品的所在行行号
                        var idx=1;
                       
                        for(i=0; i<ids.length; i++){
                            var row = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(item['commodity.sku'] == row['commodity.sku'] && 
                                '' == row.batchNo && 
                                item['storageLocation.id'] == row['storageLocation.id'] && 
                                row['gift'] == 'false'){
                                // SKU，批次号，库存地一致，并且不是赠品即认为是同一商品
                                // 因为自动完成功能所带数据一律没有批次号，所以有以空比较 ('' == row.batchNo)
                                existRowId = ids[i];
                                break;
                            }
                        }
                        
                        if(existRowId){
                            var myrowdata = $grid.jqGrid('getRowData', existRowId);//获取单行数据根据ID
                            alert("所选商品已存在[ "+myrowdata.subVoucher+" | "+myrowdata['commodity.display']+" ]，请直接编辑数量字段。");
                        }else{
                            var myrowdata = {  
                                    'commodity.sku' : item['commodity.sku'],//商品唯一性标识
                                    'commodity.id' : item['commodity.id'],
                                    'commodity.barcode' : item['commodity.barcode'],
                                    'commodity.sku' : item['commodity.sku'],
                                    'commodity.display' : item['commodity.display'],
                                    'commodity.title' : item['commodity.title'],
                                    'price' : item['commodity.price'],
                                    'measureUnit' : item['commodity.measureUnit'],
                                    'storageLocation.id' : item['storageLocation.id'],
                                    'batchNo' : item['batchNo'],
                                    'expireDate' : item['expireDate'],
                                    'quantity' : 1,
                                    'discountRate' : 0,
                                    'taxRate' : 0
                            };
                            $grid.data("gridOptions").calcRowAmount.call($grid, myrowdata);
                            existRowId = $grid.jqGrid("setEditingRowdata", myrowdata);
                           
                        }
                        var $form = $grid.closest("form");
                        $form.data("formOptions").updateTotalAmount.call($form);
                    }
                    $elem.dblclick(function() {
                        var isGift = $(this).closest("tr").find("input[name='gift']").is(":checked");
                        var rowdata = $grid.jqGrid("getEditingRowdata");
                        $(this).popupDialog({
                            url : WEB_ROOT + '/myt/stock/commodity-stock!forward?_to_=selection&isGift='+isGift,
                            postData : {
                                sku : rowdata['commodity.sku']
                            },
                            title : '选取库存商品',
                            callback : function(item) {
                                selectCommodity(item);
                            }
                        })
                        // 多选模式双击弹出选取框之后，取消当前行编辑状态
                        $grid.closest("div.ui-jqgrid-view").find(".ui-pg-div span.ui-icon-cancel").click();
                    }).autocomplete({
                        autoFocus : true,
                        source : function(request, response) {
                            var data = Biz.queryCacheCommodityDatas(request.term);
                            return response(data);
                        },
                        minLength : 2,
                        select : function(event, ui) {
                            var item = ui.item;
                            this.value = item.display;
                            // 调用回调函数
                            autocompleteSelectCommodity(item);
                            event.stopPropagation();
                            event.preventDefault();
                            return false;
                        },
                        change : function(event, ui) {
                            if (ui.item == null || ui.item == undefined) {
                                //$elem.val("");
                                $elem.focus();
                            }
                        }
                    }).focus(function() {
                        $elem.select();
                    });
                }
            },
            align : 'left'
        }, {
            label : '单位',
            name : 'measureUnit',
            editable : true,
            width : 80
        }, {
            label : '数量',
            name : 'quantity',
            width : 80,
            formatter : 'number',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            summaryType : 'sum'
        }, {
            label : '销售单价',
            name : 'price',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                required : true,
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            summaryType : 'sum'
        }, {
            label : '是否赠品',
            name : 'gift',
            width : 80,
            edittype : 'checkbox',
            editable : true,
            align : 'center',
            responsive : 'sm',
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    var $form = $elem.closest("form");
                    
                    $elem.change(function() {
                        var checked = $elem.is(":checked");
                        /*
                         * 设置赠品或者取消赠品之后可能存在重复商品，所以在此校验唯一性
                         */
                        var editingRowData = $grid.jqGrid('getEditingRowdata');
                        var ids = $grid.jqGrid('getDataIDs');// 返回当前grid里所有数据的id
                        for(i=0; i<ids.length; i++){
                            var existRowData = $grid.jqGrid('getRowData', ids[i]);//获取单行数据根据ID
                            if(editingRowData['commodity.sku'] == existRowData['commodity.sku']){
                                console.info(checked+" | "+existRowData['gift']);
                                if(checked.toString() == existRowData['gift']){
                                    // SKU一致，并且不是赠品即认为是同一商品
                                    alert("商品已存在[ "+existRowData.subVoucher+" | "+existRowData['commodity.display']+" ]," +
                                    		"请尝试先删除此行，然后编辑已存在行的数量字段。");
                                    $elem.attr("checked", !checked);
                                    return;
                                }
                            }
                        }
                        
                        var bakNode = $elem.closest('tr');// 数据备份到的节点
                        if (checked) {
                            var rowdata = $grid.jqGrid("getEditingRowdata");
                            bakNode.attr("data-bak", JSON.stringify(rowdata));//先备份数据
                            rowdata['price'] = 0;
                            rowdata['originalAmount'] = 0;
                            rowdata['discountRate'] = 0;
                            rowdata['discountAmount'] = 0;
                            rowdata['amount'] = 0;
                            rowdata['taxAmount'] = 0;
                            rowdata['commodityAndTaxAmount'] = 0;
                            $grid.jqGrid("setEditingRowdata", rowdata);
                        }else{
                            // 取消赠品勾选后还原数据
                            rowdata = JSON.parse(bakNode.attr("data-bak"));
                            $grid.jqGrid("setEditingRowdata", rowdata);
                        }
                    });
                }
            },
        }, {
            label : '原始金额',
            name : 'originalAmount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣率(%)',
            name : 'discountRate',
            width : 80,
            formatter : 'currency',
            editable : true,
            editrules : {
                number : true
            },
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '折扣额',
            name : 'discountAmount',
            width : 80,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            align : 'right',
            responsive : 'sm'
        }, {
            label : '折后金额',
            name : 'amount',
            width : 80,
            formatter : 'currency',
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid, $elem.attr("name"));
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '税率(%)',
            name : 'taxRate',
            width : 80,
            formatter : 'number',
            hidden : true,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    var $form = $elem.closest("form");
                    $elem.keyup(function() {
                        $grid.data("gridOptions").updateRowAmount.call($grid);
                    });
                }
            },
            responsive : 'sm'
        }, {
            label : '税额',
            name : 'taxAmount',
            width : 80,
            formatter : 'currency',
            hidden : true,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '含税总金额',
            name : 'commodityAndTaxAmount',
            width : 80,
            formatter : 'currency',
            hidden : true,
            editable : true,
            editoptions : {
                dataInit : function(elem) {
                    var $elem = $(elem);
                    $elem.attr("readonly", true);
                }
            },
            responsive : 'sm'
        }, {
            label : '发货仓库',
            name : 'storageLocation.id',
            width : 150,
            editable : true,
            editrules : {
                required : true
            },
            stype : 'select',
            searchoptions : {
                value : Biz.getStockDatas()
            }
        }, {
            label : '批次号',
            name : 'batchNo',
            width : 80,
            editable : true,
            editoptions : {
                placeholder : '双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.dblclick(function() {
                        $elem.closest(".jqgrow").find("input[name='commodity.display']").dblclick();
                    }).keypress(function(event) {
                        return false;
                    });
                }
            }
        }, {
            label : '批次过期日期',
            name : 'expireDate',
            width : 80,
            editable : true,
            editoptions : {
                readonly : true,
                placeholder : '双击选取',
                dataInit : function(elem) {
                    var $grid = $(this);
                    var $elem = $(elem);
                    $elem.dblclick(function() {
                        $elem.closest(".jqgrow").find("input[name='commodity.display']").dblclick();
                    }).keypress(function(event) {
                        return false;
                    });
                }
            }
        } ],
        footerrow : true,
        beforeInlineSaveRow : function(rowid) {
            var $grid = $(this);
            
            $grid.data("gridOptions").updateRowAmount.call($grid);
        },
        afterInlineSaveRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        afterInlineDeleteRow : function(rowid) {
            var $grid = $(this);
            // 整个Form相关金额字段更新
            var $form = $grid.closest("form");
            $form.data("formOptions").updateTotalAmount.call($form);
        },
        userDataOnFooter : true
    });

});
